import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import codeErrorHandle from './codeErrorHandle';
import httpErrorHandle from './httpErrorHandle';
import { errorTips, getStore, setStore } from '@/utils/utils';
import { loading as loadConfig } from './loading';
import $config from '@/config';

/**
 *获取config配置
 */
async function getConfig() {
    const configData = getStore($config.CONFIG);
    if (configData) return;
    try {
        const response = await fetch($config.CONFIG_URL + $config.CONFIG_API);
        const { data } = await response.json();
        setStore($config.CONFIG, data);
    } catch (error) {
        errorTips('获取配置失败');
        throw error;
    }
}

/**
 * http 请求
 */

const token =
    'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaSI6IjEwMDU5Mzg3IiwidWkiOiI1IiwiZXVpIjoiNjhmOGIyNzY2OTZkMGU1OTIxMDExNGI4IiwiZ2QiOiIyYTIyY2FhZS1lYzVmLTQ4MzQtYjI0Ny1jNmRkNWM3M2UzZmIiLCJscyI6IjEiLCJuYmYiOjE3NjIyNDA2MzksImV4cCI6MTc2NDgzMjYzOSwiaXNzIjoiU3RlYWR5LkFwcCIsImF1ZCI6IlN0ZWFkeS5BcHAifQ.QgsJOM3r20aJf1AXEsst8Bihqc3d8WRu3hfvpazBHWc';
const base = 'https://twines-web.smartapp.net.cn/WebApi';
const http = async ({
    url = '',
    method = 'post', //请求方式
    headers = {}, //请求头
    query = {}, //
    data = {}, //
    loading = true,
    responseType = 'undefined', //
    timeout = 60 * 1000, //
    progressCallBack = (a: any) => {},
}) => {
    loadConfig.value = loading;
    await getConfig();
    const config = getStore($config.CONFIG);

    const axiosParams: AxiosRequestConfig = {
        // url: config.baseApi + url,
        url,
        method,
        params: query,
        data,
        responseType: responseType == 'blob' ? 'blob' : undefined,
        timeout,
        headers: {
            // Authorization: `Bearer ${getStore($config.USERINFO)?.token}`,
            Authorization: token,
            ...headers,
        },

        onUploadProgress: (progressEvent: any) => {
            if (typeof progressCallBack === 'function') {
                progressCallBack(progressEvent);
            }
        },
    };

    return axios
        .request(axiosParams)
        .then(res => {
            loadConfig.value = false;
            // 文件流，直接返回
            if (responseType === 'blob') {
                return Promise.resolve(res);
            }
            const resData = res.data || {};

            const { code } = resData;

            if (code != 1) {
                codeErrorHandle(code);
                return Promise.resolve(resData);
            }

            return Promise.resolve(resData);
        })
        .catch(err => {
            loadConfig.value = false;
            httpErrorHandle(err?.status);
            return Promise.resolve(err);
        });
};

export default http;
